#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 错误处理
die() {
    echo -e "${RED}[错误] $1${NC}" >&2
    read -p "按回车键返回主菜单..."
    return 1
}

# 获取本机IP地址
get_local_ip() {
    ip -o -4 addr show | awk '{print $4}' | cut -d'/' -f1 | grep -v '127.0.0.1' | head -n1
}

# 精准系统检测
detect_system() {
    if [ -f /etc/synoinfo.conf ] && [ -d /var/packages ]; then
        echo "dsm"
        return
    fi

    if grep -q "ID=debian" /etc/os-release && ls /vol1* &>/dev/null; then
        echo "fnos"
        return
    fi

    if grep -q "ID=debian" /etc/os-release; then
        echo "debian"
        return
    fi

    if [ -f /etc/os-release ]; then
        echo "linux"
        return
    fi

    echo "unknown"
}

# 获取Docker目录
get_docker_dir() {
    local system_type=$1
    local dir=""

    case $system_type in
        "dsm")
            # 查找现有的 docker 目录，找到就用第一个
            dir=$(find /volume* -maxdepth 1 -type d -name "docker" 2>/dev/null | head -n1)
            # 如果没找到，就使用默认路径 /volume1/docker
            [ -z "$dir" ] && dir="/volume1/docker"
            ;;
        "fnos")
            # 查找现有的 docker 目录，找到就用第一个
            dir=$(find /vol*/1000 -maxdepth 1 -type d -name "docker" 2>/dev/null | head -n1)
            # 如果没找到，就使用默认路径 /vol1/1000/docker
            [ -z "$dir" ] && dir="/vol1/1000/docker"
            ;;
        *)
            # 其他系统直接使用 /opt/docker
            dir="/opt/docker"
            ;;
    esac

    # 清理路径中的特殊字符
    dir=$(echo "$dir" | tr -d '\n\r')
    
    # 创建目录（如果不存在）
    mkdir -p "$dir" || die "无法创建目录 $dir"
    
    echo "$dir"
}

# 安装RustDesk服务端
install_rustdesk_server() {
    local base_dir="$1"
    local data_dir="${base_dir}/rustdesk/data"
    
    echo -e "${BLUE}[信息] 正在安装RustDesk服务端...${NC}"
    
    # 创建数据目录
    mkdir -p "$data_dir" || die "无法创建RustDesk数据目录: $data_dir"
    chmod 777 "$data_dir" || echo -e "${YELLOW}[警告] 无法设置目录权限${NC}"

    # 获取域名
    local ip=$(get_local_ip)
    read -p "请输入您的域名(直接回车使用IP $ip): " domain
    [ -z "$domain" ] && domain="$ip"

    # 获取端口配置
    echo -e "${YELLOW}请输入服务端端口配置(直接回车使用默认端口)${NC}"
    read -p "TCP端口21115(默认21115): " port_21115
    [ -z "$port_21115" ] && port_21115="21115"
    
    read -p "TCP端口21116(默认21116): " port_21116
    [ -z "$port_21116" ] && port_21116="21116"
    
    read -p "UDP端口21116(默认21116): " port_21116_udp
    [ -z "$port_21116_udp" ] && port_21116_udp="21116"
    
    read -p "TCP端口21117(默认21117): " port_21117
    [ -z "$port_21117" ] && port_21117="21117"
    
    read -p "TCP端口21118(默认21118): " port_21118
    [ -z "$port_21118" ] && port_21118="21118"
    
    read -p "TCP端口21119(默认21119): " port_21119
    [ -z "$port_21119" ] && port_21119="21119"

    # 清理旧容器
    if docker ps -aq --filter "name=rustdesk-server"; then
        echo -e "${YELLOW}[注意] 移除已存在的rustdesk-server容器...${NC}"
        docker stop rustdesk-server >/dev/null 2>&1
        docker rm rustdesk-server >/dev/null 2>&1
    fi

    # 运行新容器
    echo -e "${BLUE}[信息] 正在启动RustDesk服务端容器...${NC}"
    if ! docker run -d \
        --name rustdesk-server \
        --restart=always \
        -p ${port_21115}:21115 \
        -p ${port_21116}:21116 \
        -p ${port_21116_udp}:21116/udp \
        -p ${port_21117}:21117 \
        -p ${port_21118}:21118 \
        -p ${port_21119}:21119 \
        -e "RELAY=${domain}:${port_21117}" \
        -e "ENCRYPTED_ONLY=1" \
        -v "${data_dir}:/data" \
        rustdesk/rustdesk-server-s6:latest; then
        docker logs rustdesk-server 2>&1 | head -n 20
        die "启动RustDesk服务端容器失败"
    fi

    # 验证容器状态
    sleep 3
    if ! docker ps --filter "name=rustdesk-server" --format "{{.Status}}" | grep -q "Up"; then
        docker logs rustdesk-server 2>&1 | head -n 20
        die "容器启动后异常退出"
    fi

    echo -e "\n${GREEN}========== RustDesk服务端安装成功 ==========${NC}"
    echo -e "服务端地址: ${GREEN}${domain}${NC}"
    echo -e "已配置的端口:"
    echo -e "  - TCP: ${port_21115}, ${port_21116}, ${port_21117}, ${port_21118}, ${port_21119}"
    echo -e "  - UDP: ${port_21116_udp}"
    echo -e "数据目录: ${data_dir}"
    echo -e "查看日志: ${YELLOW}docker logs rustdesk-server${NC}"
    read -p "按回车键返回主菜单..."
}

# 安装RustDesk API
install_rustdesk_api() {
    local base_dir="$1"
    local api_dir="${base_dir}/rustdesk/apidata"
    local port=7000
    
    echo -e "${BLUE}[信息] 正在安装RustDesk API...${NC}"
    
    # 创建API数据目录
    mkdir -p "$api_dir" || die "无法创建API数据目录: $api_dir"
    chmod 777 "$api_dir" || die "无法设置API目录权限"

    # 获取端口
    read -p "请输入API端口(默认7000): " input_port
    [ -n "$input_port" ] && port="$input_port"

    # 清理旧容器
    if docker ps -aq --filter "name=rustdesk-api"; then
        echo -e "${YELLOW}[注意] 移除已存在的rustdesk-api容器...${NC}"
        docker stop rustdesk-api >/dev/null 2>&1
        docker rm rustdesk-api >/dev/null 2>&1
    fi

    # 运行新容器
    echo -e "${BLUE}[信息] 正在启动RustDesk API容器...${NC}"
    if ! docker run -d \
        --name rustdesk-api \
        --restart=always \
        -p ${port}:80 \
        -v "${api_dir}:/var/www/data" \
        v5star/rustdesk-api; then
        docker logs rustdesk-api 2>&1 | head -n 20
        die "启动RustDesk API容器失败"
    fi

    # 验证容器状态
    sleep 3
    if ! docker ps --filter "name=rustdesk-api" --format "{{.Status}}" | grep -q "Up"; then
        docker logs rustdesk-api 2>&1 | head -n 20
        die "容器启动后异常退出"
    fi

    local ip=$(get_local_ip)
    echo -e "\n${GREEN}========== RustDesk API安装成功 ==========${NC}"
    echo -e "API访问地址: ${GREEN}http://${ip}:${port}${NC}"
    echo -e "数据目录: ${api_dir}"
    echo -e "查看日志: ${YELLOW}docker logs rustdesk-api${NC}"
    echo -e "\n${YELLOW}初始化说明:${NC}"
    echo -e "1. 访问上述API地址进行初始化"
    echo -e "2. 添加用户: http://${ip}:${port}/index.php?ac=add&u=用户名&p=密码"
    echo -e "3. 删除用户: http://${ip}:${port}/index.php?ac=del&u=用户名&p=密码"
    read -p "按回车键返回主菜单..."
}

# 显示菜单
show_menu() {
    clear
    echo -e "${BLUE}=== RustDesk安装菜单 ===${NC}"
    echo -e "1. 安装RustDesk服务端"
    echo -e "2. 安装RustDesk API"
    echo -e "3. 安装完整服务(服务端+API)"
    echo -e "0. 退出"
    echo -ne "${YELLOW}请输入选择: ${NC}"
}

# 主流程
main() {
    # 检查Docker
    if ! command -v docker &>/dev/null; then
        die "Docker未安装，请先安装Docker"
    fi
    echo -e "${GREEN}[成功] Docker已安装: $(docker --version | cut -d ',' -f 1)${NC}"

    # 检测系统并获取目录
    system_type=$(detect_system)
    case $system_type in
        "dsm") echo -e "${GREEN}[系统] 检测到群辉DSM${NC}" ;;
        "fnos") echo -e "${GREEN}[系统] 检测到FNOS${NC}" ;;
        "debian") echo -e "${YELLOW}[系统] 检测到Debian${NC}" ;;
        "linux") echo -e "${YELLOW}[系统] 检测到通用Linux${NC}" ;;
        *) echo -e "${YELLOW}[警告] 系统类型未知，使用默认配置${NC}" ;;
    esac

    dir=$(get_docker_dir "$system_type")
    echo -e "${BLUE}[目录] 使用容器目录: ${dir}${NC}"

    while true; do
        show_menu
        read choice
        case $choice in
            1) install_rustdesk_server "$dir" ;;
            2) install_rustdesk_api "$dir" ;;
            3) 
                install_rustdesk_server "$dir"
                if [ $? -eq 0 ]; then
                    install_rustdesk_api "$dir"
                fi
                ;;
            0) echo -e "${GREEN}退出安装脚本${NC}"; exit 0 ;;
            *) echo -e "${RED}无效选择，请重新输入${NC}"; sleep 1 ;;
        esac
    done
}

main "$@"